package com.example.traning.mall.dal.redis.dict;

import cn.hutool.core.collection.CollUtil;
import com.example.traning.mall.framework.common.util.json.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * @author lei yu
 * @date 2024/05/21
 */
@Slf4j
@Repository
@RequiredArgsConstructor
public class DictDistrictRedisDAO {

    private final StringRedisTemplate redisTemplate;

    /**
     * 缓存数据的KEY的前缀：根据父级存储的地区列表
     */
    private final static String KEY_PREFIX_LIST_BY_PARENT = "district:list-by-parent:";

    /**
     * 缓存数据的KEY的前缀：地区数据
     */
    private final static String KEY_PREFIX_ITEM = "district:item:";

    /**
     * 缓存中所有列表数据的Key集合的Key
     */
    private final static String KEY_ALL_KEYS = "district:keys";


    public void save(DictDistrictPO po) {
        log.debug("开始处理【存储地区数据】的缓存数据访问，地区数据：{}", po);
        String key = KEY_PREFIX_ITEM + po.getCode();
        SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
        opsForSet.add(KEY_ALL_KEYS, key);
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, JsonUtils.toJsonString(po));
    }


    public void saveListByParent(Long parentId, List<DictDistrictPO> districtList) {
        log.debug("开始处理【存储根据父级划分的地区列表】的缓存数据访问，父级地区ID：{}，地区列表：{}", parentId, districtList);
        String key = KEY_PREFIX_LIST_BY_PARENT + parentId;
        SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
        opsForSet.add(KEY_ALL_KEYS, key);
        ListOperations<String, String> opsForList = redisTemplate.opsForList();
        for (DictDistrictPO item : districtList) {
            opsForList.rightPush(key, JsonUtils.toJsonString(item));
        }
    }

    public void deleteAll() {
        log.debug("开始处理【删除所有的地区列表数据】的缓存数据访问，无参数");
        SetOperations<String, String> opsForSet = redisTemplate.opsForSet();
        Set<String> keys = opsForSet.members(KEY_ALL_KEYS);
        redisTemplate.delete(keys);
    }

    public List<DictDistrictPO> listByParent(Long parentId) {
        log.debug("开始处理【根据父级查询子级地区列表】的缓存数据访问，父级地区ID：{}", parentId);
        String key = KEY_PREFIX_LIST_BY_PARENT + parentId;
        long start = 0;
        long end = -1;
        ListOperations<String, String> opsForList = redisTemplate.opsForList();
        List<String> list = opsForList.range(key, start, end);
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newArrayList();
        }
        return list.stream().map(str -> JsonUtils.parseObject(str, DictDistrictPO.class)).toList();
    }
}
